//给多级对象属性赋值
const setNextObjValue = (obj, list, mKey, mValue) => {
  let nextItem = ""
  const nextObj = (obj, key) => obj[key] = obj[key] || {}
  list.forEach((key, index) => nextItem = nextObj(index == 0 ? obj : nextItem, key))
  nextItem[mKey] = mValue
}

let genObj = {
  readState: 0,//0:未开始，1：已开始
  currentKey: '',//当前的key
  currentData: '',//当前的值
  parentKeys: [],//父级的key数组
  startEnd(char) {
    console.log("startEnd====start", {
      readState: this.readState,
      currentKey: this.currentKey,
      currentData: this.currentData,
      parentKeys: this.parentKeys
    })
    if (char == '"' && this.currentKey) {
      return
    }
    if (this.readState == 1 && !this.currentKey) {//读取结束，给key赋值
      this.currentKey = this.currentData
    } else if (this.readState == 1 && this.currentKey) {//读取结束，给value赋值
      if (this.parentKeys.length) {
        setNextObjValue(this, this.parentKeys, this.currentKey, this.currentData)
        if (char == "}") this.parentKeys.pop()
      } else {
        this[this.currentKey] = this.currentData
      }
      this.currentKey = ""
    }
    if (this.readState == 1) {//读取结束
      this.currentData = ""
    }
    this.readState = this.readState == 0 ? 1 : 0
    console.log("startEnd====end", {
      readState: this.readState,
      currentKey: this.currentKey,
      currentData: this.currentData,
      parentKeys: this.parentKeys
    })
  },
  readChar(char) {
    this.currentData += char
  },
  addChild() {
    if (this.currentKey) {
      this.parentKeys.push(this.currentKey)
      this.currentKey = ""
      this.readState = 0
    }
  },
  getData() {
    let obj = {}, list = ['readState', 'currentKey', 'currentData',
      'parentKeys', 'startEnd', 'readChar', 'addChild', 'getData']
    Object.keys(this).filter(key => !list.includes(key)).forEach(key => obj[key] = this[key])
    return obj
  }
}
//==============================================
//==============================================
let testObj = {
  bbb: {
    ccc: 222,
    dddd: {
      kkk: 333
    }
  }
}
let testStr = JSON.stringify(testObj)
console.log(testStr)

// {"bbb":{"ccc":22,"dddd":{"kkk":33}}}
//==============================================
for (let i = 0; i < testStr.length; i++) {
  let char = testStr[i]
  console.log("\n")
  console.log(`genObj====【${i}】___【${char}】`)
  if (char == "{") {
    genObj.addChild()
  } else if (char == '"' || char == ':' || char == '}' || char == ',') {
    genObj.startEnd(char)
  } else {
    genObj.readChar(char)
  }
  console.log("genObj====", genObj.getData())
}

